/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.doeacc.tms.web.bean.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import edu.doeacc.tms.domain.Customer;
import edu.doeacc.tms.web.bean.CustomerBean;

/**
 *
 * @author slok
 */
@FacesConverter(forClass=Customer.class)
public class CustomerConverter implements Converter {


    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uic, String value) {
         if (value == null || value.length() == 0) {
                return null;
            }
            CustomerBean controller = (CustomerBean) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "customerBean");
            return controller.getCustomerFacade().find(Long.valueOf(value));
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Customer) {
            Customer o = (Customer) object;
            return String.valueOf(o.getId());
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Customer.class.getName());
        }
    }

}
